const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const { Pool } = require('pg');

// 从环境变量获取数据库配置
const pool = new Pool({
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  database: process.env.DB_NAME,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD
});

// JWT密钥（从环境变量获取，如未设置则使用默认值）
const JWT_SECRET = process.env.JWT_SECRET || 'smart-restaurant-secret-key-2024';
const JWT_EXPIRES_IN = '7d';

/**
 * 用户登录验证
 * POST /api/auth/login
 */
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;

    // 验证必填字段
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        message: '用户名和密码不能为空'
      });
    }

    // 查询用户信息
    const client = await pool.connect();
    try {
      const query = 'SELECT * FROM users WHERE username = $1';
      const result = await client.query(query, [username]);

      if (result.rows.length === 0) {
        return res.status(401).json({
          success: false,
          message: '用户名或密码错误'
        });
      }

      const user = result.rows[0];

      // 验证密码
      const isPasswordValid = bcrypt.compareSync(password, user.password);
      
      if (!isPasswordValid) {
        return res.status(401).json({
          success: false,
          message: '用户名或密码错误'
        });
      }

      // 生成JWT token
      const token = jwt.sign(
        {
          userId: user.id,
          username: user.username,
          role: user.role
        },
        JWT_SECRET,
        { expiresIn: JWT_EXPIRES_IN }
      );

      // 更新最后登录时间
      await client.query(
        'UPDATE users SET updated_at = NOW() WHERE id = $1',
        [user.id]
      );

      // 返回登录成功信息
      res.json({
        success: true,
        message: '登录成功',
        data: {
          token,
          user: {
            id: user.id,
            username: user.username,
            role: user.role
          }
        }
      });
    } finally {
      client.release();
    }
  } catch (error) {
    console.error('登录失败:', error);
    res.status(500).json({
      success: false,
      message: '登录失败，请稍后重试'
    });
  }
});

/**
 * 验证用户登录状态
 * GET /api/auth/verify
 */
router.get('/verify', async (req, res) => {
  try {
    // 从请求头获取token
    const authHeader = req.headers.authorization;
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return res.status(401).json({
        success: false,
        message: '未提供认证token'
      });
    }

    const token = authHeader.substring(7);

    // 验证token
    let decoded;
    try {
      decoded = jwt.verify(token, JWT_SECRET);
    } catch (err) {
      if (err.name === 'TokenExpiredError') {
        return res.status(401).json({
          success: false,
          message: 'token已过期，请重新登录'
        });
      }
      return res.status(401).json({
        success: false,
        message: '无效的token'
      });
    }

    // 查询用户信息（确认用户仍然存在）
    const client = await pool.connect();
    try {
      const query = 'SELECT id, username, role FROM users WHERE id = $1';
      const result = await client.query(query, [decoded.userId]);

      if (result.rows.length === 0) {
        return res.status(401).json({
          success: false,
          message: '用户不存在'
        });
      }

      const user = result.rows[0];

      // 返回用户信息
      res.json({
        success: true,
        message: 'token有效',
        data: {
          user: {
            id: user.id,
            username: user.username,
            role: user.role
          }
        }
      });
    } finally {
      client.release();
    }
  } catch (error) {
    console.error('验证token失败:', error);
    res.status(500).json({
      success: false,
      message: '验证失败，请稍后重试'
    });
  }
});

/**
 * 认证中间件（用于保护需要登录的路由）
 */
const authMiddleware = async (req, res, next) => {
  try {
    const authHeader = req.headers.authorization;
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return res.status(401).json({
        success: false,
        message: '未提供认证token'
      });
    }

    const token = authHeader.substring(7);

    try {
      const decoded = jwt.verify(token, JWT_SECRET);
      req.user = decoded;
      next();
    } catch (err) {
      return res.status(401).json({
        success: false,
        message: err.name === 'TokenExpiredError' ? 'token已过期' : '无效的token'
      });
    }
  } catch (error) {
    console.error('认证中间件错误:', error);
    res.status(500).json({
      success: false,
      message: '认证失败'
    });
  }
};

/**
 * 角色验证中间件（验证用户角色）
 */
const roleMiddleware = (allowedRoles) => {
  return (req, res, next) => {
    if (!req.user) {
      return res.status(401).json({
        success: false,
        message: '未认证'
      });
    }

    if (!allowedRoles.includes(req.user.role)) {
      return res.status(403).json({
        success: false,
        message: '权限不足'
      });
    }

    next();
  };
};

/**
 * 获取当前用户信息
 * GET /api/auth/me
 */
router.get('/me', authMiddleware, async (req, res) => {
  try {
    const client = await pool.connect();
    try {
      const query = 'SELECT id, username, role, created_at FROM users WHERE id = $1';
      const result = await client.query(query, [req.user.userId]);

      if (result.rows.length === 0) {
        return res.status(404).json({
          success: false,
          message: '用户不存在'
        });
      }

      res.json({
        success: true,
        data: {
          user: result.rows[0]
        }
      });
    } finally {
      client.release();
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户信息失败'
    });
  }
});

/**
 * 用户登出
 * POST /api/auth/logout
 */
router.post('/logout', authMiddleware, (req, res) => {
  // JWT是无状态的，客户端删除token即可实现登出
  res.json({
    success: true,
    message: '登出成功'
  });
});

// 导出路由和中间件
module.exports = router;
module.exports.authMiddleware = authMiddleware;
module.exports.roleMiddleware = roleMiddleware;